/**
 * Copyright (c) 2025. joleye.com all rights reserved..
 * select选择器 0.0.1
 * @anther joleye
 * https://github.com/joleye/toolbar
 */
function jquery_select($) {
    $.fn.select = function (options) {
        $(document.body).on('click', function (event) {
            $('.el-select-popup').remove();
        });

        this.each(function () {
            var name = $(this).attr('name');
            var field = $(this).attr('data-field');
            var oid = 'el-select-o-' + new Date().getTime();
            var id = 'el-select-' + new Date().getTime();
            $(this).attr('id', oid);
            if (options === 'reset') {
                var $p = $(this).parents('.el-select-wrapper');
                if ($p.length > 0) {
                    var old_id = $p.data('ref');
                    $('#' + old_id).show().attr('name', name).attr('data-field', field);
                    $p.remove();
                }
                return;
            }
            $(this).removeAttr('name');
            $(this).removeAttr('data-field');
            var $ori = $(this);
            var cls = $(this).attr('class');
            var css = $ori.attr('style');
            var style;
            if (css) {
                style = 'style="' + css + '"';
            } else {
                style = '';
            }
            $(this).hide();
            var value = $(this).data('value');
            var wrapper = `<div class="el-select-wrapper" id="${id}" data-ref="${oid}"><input type="text" class="el-select-input ${cls}" ${style}/><input class="el-select-value" type="hidden" name="${name}" data-field="${field}"/>`;
            var svg = '<span class="el-select-suffix el-select-suffix-icon"><svg data-v-bfc1edcf="" fill="none" viewBox="0 0 24 24" width="1em" height="1em" class="t-icon t-icon-chevron-down" style="fill: none;"><g id="chevron-down"><path id="stroke1" stroke="currentColor" d="M17.5 9.5L12 15L6.5 9.5" stroke-linecap="square" stroke-width="2"></path></g></svg></span>';
            wrapper += svg;
            wrapper += '</div>';
            $(this).before(wrapper);
            var $that = $('#' + id);
            var $input = $that.find('.el-select-input');
            var $value = $that.find('.el-select-value');

            var url = $(this).data('url') || options.url;
            var keyField = $(this).data('key_field') || options.keyField;
            var method = $(this).data('method') || options.method;
            var params = $(this).data('params') || options.params || {};

            $input.attr('placeholder', options.placeholder);

            var data = [];
            $(this).find('option').each(function () {
                data.push({label: $(this).text(), value: $(this).val()});
            });

            $input.click(function (e) {
                if (url) {
                    var key = $(this).val();
                    getRemoteData(key, false);
                } else {
                    bind(data, false);
                }
                e.stopPropagation();
            });

            //有初始值
            if (value) {
                if (url) {
                    getRemoteData(value, true);
                } else {
                    bind(data, true);
                }
            }

            var el_st = null;
            $input.on('input', function (e) {
                var key = $(this).val();
                if (url) {
                    el_st && clearTimeout(el_st);
                    el_st = setTimeout(function () {
                        getRemoteData(key, false);
                    }, 200);
                } else {
                    var new_data = [];
                    for (var i = 0; i < data.length; i++) {
                        if (data[i].label.indexOf(key) > -1) {
                            new_data.push({label: data[i].label, value: data[i].value});
                        }
                    }
                    bind(new_data, false);
                }
                e.stopPropagation();
            })

            function getRemoteData(key, close) {
                var post_data = params;
                if (typeof key != "undefined") {
                    post_data[keyField] = key;
                }
                if (method === 'get') {
                    $.get(url, post_data, function (res) {
                        if (res.status) {
                            bind(res.rows, close);
                        }
                    });
                } else {
                    $.post(url, post_data, function (res) {
                        if (res.status) {
                            bind(res.rows, close);
                        }
                    });
                }
            }

            function getElementPositionWithTransform(el) {
                if (!el || el.nodeType !== 1) { // 校验：必须是有效的DOM元素
                    return {x: 0, y: 0};
                }

                // 1. 获取元素相对于视口的位置（已包含transform影响）
                var rect = el.getBoundingClientRect();

                // 2. 获取页面滚动量（视口相对于页面顶部/左侧的偏移）
                var scrollX = window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft;
                var scrollY = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;

                // 3. 计算绝对位置：视口坐标 + 页面滚动量
                var x = rect.left + scrollX;
                var y = rect.top + scrollY;

                return {x, y};
            }

            function bind(rows, noShow) {
                $('.el-select-popup').remove();

                var w = getElementPositionWithTransform($that[0]);

                var top = w.y + parseInt($that.height());
                var left = w.x;
                var min_width = parseInt($input.width());
                var html = '<div class="el-select-popup" style="position: absolute; top: ' + top + 'px; left: ' + left + 'px;min-width:' + min_width + 'px" data-bs-toggle="popover">';
                html += `<ul class="el-select__dropdown">`;
                html += '</ul>';
                html += '</div>';
                var $ul = $(html).appendTo(document.body);
                for (var i = 0; i < rows.length; i++) {
                    var e = rows[i];
                    if (options.format) {
                        e = options.format(e);
                    }
                    var hover = '';
                    if (e.value == value) {
                        hover = 'hover';
                    }
                    var li = '<li class="el-select__dropdown-item ' + hover + '" data-value="' + e.value + '">' + e.label + '</li>';
                    var $li = $(li).appendTo($ul.find('.el-select__dropdown'));
                    $li.data('row', e);
                }
                $ul.find('li').click(function (e) {
                    $value.val($(this).data('value')).data('row', $(this).data('row'));
                    value = $(this).data('value');
                    var text = $(this).text();
                    if (options.textFormat) {
                        text = options.textFormat.call($value, text);
                    }
                    $input.val(text);
                    options.change && options.change.call($value);

                    setTimeout(function () {
                        $('.el-select-popup').remove();
                    }, 50);
                    e.stopPropagation();
                });

                if (value && noShow) {
                    $ul.find('li').each(function () {
                        if ($(this).data('value') === value) {
                            $(this).click();
                        }
                    });
                }

                if (noShow) {
                    $ul.remove();
                }
            }
        });
    };
}

if (typeof define != 'undefined') {
    define(['jquery'], jquery_select);
} else if (typeof $ != 'undefined') {
    jquery_select($);
}
